package com.submit.demo.service.impl;

import com.submit.demo.config.MinIOProperties;
import com.submit.demo.model.SubTask;
import com.submit.demo.model.Word;
import com.submit.demo.repository.SubTaskRepository;
import com.submit.demo.service.SubTaskService;
import com.submit.demo.util.MinIOUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class SubTaskServiceImpl implements SubTaskService {
    @Autowired
    private SubTaskRepository subTaskRepository;

    @Autowired
    private MinIOProperties minIOProperties;

    @Override
    public Integer impSubTasks(String tid, List<String> sids) {
        List<SubTask> list = new ArrayList<>();
        for(String sid : sids){
            SubTask subTask = new SubTask();
            subTask.setTid(tid);
            subTask.setSid(sid);
            subTask.setStatus(0);
            list.add(subTask);
        }
        subTaskRepository.insert(list);
        return 1;
    }

    @Override
    public Integer upload(String sid, String tid, MultipartFile[] files) {
        SubTask subTask = subTaskRepository.findSubTaskBySidAndTid(sid, tid);
        subTask.setStatus(1);
        if(subTask.getWords() == null){
            subTask.setWords(new ArrayList<>());
        }
        List<Word> list = new ArrayList<>();
        for(MultipartFile word : files){
            Word w = new Word();
            String name = word.getOriginalFilename();
            w.setWord(name);
            w.setSubTime(new Date());
            list.add(w);
            try {
                MinIOUtil.upload(minIOProperties.getBucketName(), name, word.getInputStream(), word.getSize());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        subTask.getWords().addAll(list);
        subTaskRepository.save(subTask);
        return 1;
    }

    @Override
    public SubTask findOne(String sid, String tid) {
        return subTaskRepository.findSubTaskBySidAndTid(sid, tid);
    }
}
